//
//  LSRMeTableController.m
//  BaiSiProject
//
//  Created by lshenrong on 16/7/3.
//  Copyright © 2016年 lshenrong. All rights reserved.
//
#import <AFNetworking.h>

#import "LSRMeTableController.h"
#import "LSRSettingViewController.h"
#import "LSRSquareCell.h"
#import <SafariServices/SafariServices.h>
#import "LSRwebViewController.h"

#import <MJExtension.h>
#import "LSRSquareItem.h"
#define itemWH ((LSRScreenW-(cols-1)*margin)/cols)
@interface LSRMeTableController ()<UICollectionViewDataSource,UICollectionViewDelegate>
/**<#name#>*/
@property(strong,nonatomic  )NSMutableArray *itemArray;

@property(weak,nonatomic)UICollectionView *collectionView;


@end


@implementation LSRMeTableController
//    重用标识,为了防止被修改，用const修饰
static NSString  * const ID=@"cell";

//设置列数
 static  NSInteger cols=4;
//设置间距
 static CGFloat margin=1;
// 设置item的宽高,放在外面设置会报警 Initializer element is not a compile-time constant，设置宏就不会了
//CGFloat itemWH=(LSRScreenW-(cols-1)*margin)/cols;


- (void)viewDidLoad {
    
    [super viewDidLoad];
    
    [self setNavigationBar];
    
    //设置底部展示的CollectionView
    [self setFootView];
//   获取数据
    [self loadData];

    

}

-(void)setFootView



{
    //创建流水布局
    UICollectionViewFlowLayout *layout= [self setupLayOut];
    //创建collectionView
    UICollectionView *collectionView=[self  setUpWithLayout:layout];
    
    //为什么不能添加子控件形式加入collectionView
    //    [self.tableView.tableFooterView addSubview:collectionView];
    self.tableView.tableFooterView=collectionView;
}
#pragma mark-- 获取数据
-(void)loadData
{
    
    
    //看接口文档--
    //创建会话
    AFHTTPSessionManager *manager=[AFHTTPSessionManager manager];
    // 设置请求参数
    NSMutableDictionary *squareDict=[NSMutableDictionary dictionary];
    squareDict[@"a"]=@"square";
    squareDict[@"c"]=@"topic";
    
    [manager GET:@"http://api.budejie.com/api/api_open.php" parameters:squareDict progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        //写入plist文件
        //        [responseObject writeToFile:@"/Users/lshenrong/Desktop/data/square.plist" atomically:YES];
        
        //字典数组转为模型数组
        NSArray *squarArray=responseObject[@"square_list"];
        
        
        self.itemArray=[LSRSquareItem mj_objectArrayWithKeyValuesArray:squarArray];
        
        //模仿格子数没有铺满collectionVeiw的情形
        [self.itemArray removeLastObject];
        [self resolveData];
        
        // 计算总行数 = (count - 1) / cols + 1
        NSInteger rows=(self.itemArray.count-1)/cols+1;
        //计算collectionView的高度
        CGFloat collectionH=itemWH*rows+(rows-1)*margin;
        //让collectionView的高度等于需要展示内容的高度，collectionView就不用滚动了，只随着tableVeiw滚动
        self.collectionView.xmg_height=collectionH;
        //解决tableView不能滚动的bug,tableView自动计算设置滚动范围
        self.tableView.tableFooterView=self.collectionView;
        
        //  是刷新collectionView的数据才会来到，不是刷新 [self.tableView reloadData];collectionView的数据源方法
        
        [self.collectionView reloadData];
//        NSLog(@"%@",self.itemArray);
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        NSLog(@"%@",error);
        
        
    }];
    
    
    
}
-(void)resolveData
{   //没有填满的格子
    NSInteger extra=self.itemArray.count%cols;
    if (extra) {
        extra=cols-extra;
        for (int i=0; i<extra; i++) {
            LSRSquareItem *item=[LSRSquareItem new];
            [self.itemArray addObject:item];
        }
        
    }
  

}

//创建流水布局
-(UICollectionViewFlowLayout *)setupLayOut
{

    //注意是流水线布局才有那样的效果
    //  UICollectionViewLayout *layout=[[UICollectionViewLayout alloc] init];
    
    UICollectionViewFlowLayout *layout=[[ UICollectionViewFlowLayout alloc] init];
    
  
    //设置cell的大小
    layout.itemSize=CGSizeMake(itemWH, itemWH);
    //    设置间距
    layout.minimumLineSpacing=margin;
    layout.minimumInteritemSpacing=margin;
    
    return layout;
}
//创建collectionView

-(UICollectionView *)setUpWithLayout:(UICollectionViewFlowLayout *)layout
{

    UICollectionView *collectionView=[[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, LSRScreenW, 200) collectionViewLayout:layout];
    
    self.collectionView=collectionView;
    
    //设置数据源代理
    collectionView.dataSource=self;
    //设置代理,监听点击事件
    collectionView.delegate=self;
    
    collectionView.backgroundColor=[UIColor clearColor];
    //必须使用注册制
    //  [collectionView registerClass:NSStringFromClass([UICollectionViewCell  class]) forCellWithReuseIdentifier:ID];
    //    [collectionView registerClass:[LSRSquareCell class] forCellWithReuseIdentifier:ID];
    
    //xib描述的cell要用另外的注册方式
    
    [collectionView registerNib:[UINib nibWithNibName:@"LSRSquareCell" bundle:nil] forCellWithReuseIdentifier:ID];
    
    
 
    
    NSLog(@"%f",self.tableView.tableHeaderView.xmg_height);
    //设置tableVeiw之间的间距
    self.tableView.sectionHeaderHeight=0;
    self.tableView.sectionFooterHeight=10;
    self.tableView.contentInset=UIEdgeInsetsMake(-25, 0, 0, 0);
    
    return collectionView;

}






#pragma mark --UICollectionViewDataSource
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
//
//    NSLog(@"----------------------------%@",self.itemArray);
    return self.itemArray.count;

}

- (LSRSquareCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath


{

//    后面带 forIndexPath，一定要用注册式
   LSRSquareCell *cell=[collectionView dequeueReusableCellWithReuseIdentifier:ID forIndexPath:indexPath];
    
    cell.backgroundColor=[UIColor whiteColor];
    //冲洗item的set方法
    cell.item=self.itemArray[indexPath.row];//row用item代替也可，这个item是collection的item

   
    return cell;

}
//点击collectionView的cell跳转到相应的界面
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath


{
    //取出响应的模型
    LSRSquareItem *item=self.itemArray[indexPath.row];

    
    if (![item.url containsString:@"http"]) return;

//    
//    SFSafariViewController *sfVC=[[SFSafariViewController alloc] initWithURL:[NSURL URLWithString:item.url]];
//    
//    [self presentViewController:sfVC animated:YES completion:nil];
    LSRwebViewController *webVC=[[LSRwebViewController alloc] init];
    
    webVC.hidesBottomBarWhenPushed=YES;
    webVC.url=[NSURL URLWithString:item.url];
    
    [self.navigationController pushViewController:webVC animated:YES];
}




-(void)setNavigationBar

{    //设置左边的item
    UIBarButtonItem *settingItem1=[UIBarButtonItem itemWithimage:[UIImage imageNamed:@"mine-setting-icon"] highlightImage:[UIImage imageNamed:@"mine-setting-icon-click"] Target:self action:@selector(click) forControlEvents:UIControlEventTouchUpInside];
    
    //设置右边的item
    UIBarButtonItem *nightItem2=[UIBarButtonItem itemWithimage:[UIImage imageNamed:@"mine-moon-icon"] selImage:[UIImage imageNamed:@"mine-moon-icon-click"] Target:self action:@selector(nightClick:) forControlEvents:UIControlEventTouchUpInside];
    
    
    
    
    self.navigationItem.rightBarButtonItems=@[settingItem1,nightItem2];
}
-(void)click
{
    
    LSR__fnc__;
    LSRSettingViewController *setVC=[[LSRSettingViewController alloc] init];
    
    setVC.hidesBottomBarWhenPushed=YES;//这句要写在push之前
    //跳转到设置控制器
    [self.navigationController pushViewController:setVC animated:YES];
    
    //self.navigationItem.leftBarButtonItem ,错误，不能设置在push之后
    
}
-(void)nightClick:(UIButton *)btn
{
    LSR__fnc__;
//  btn.enabled=NO;
    btn.selected=!btn.selected;


}
@end
